package com.qianfeng.android.baoman.fragment;


import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.qianfeng.android.baoman.MainActivity;
import com.qianfeng.android.baoman.R;
import com.qianfeng.android.baoman.TopicPagerMovieActivity;
import com.qianfeng.android.baoman.TopicPicturesDetailActivity;
import com.qianfeng.android.baoman.adapter.CommonFragmentAdapter;
import com.qianfeng.android.baoman.adapter.TopicArticleAdapter;
import com.qianfeng.android.baoman.model.Article;
import com.qianfeng.android.baoman.model.Jokable;
import com.qianfeng.android.baoman.model.JokePoint;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.LinkedList;

/**
 * A simple {@link Fragment} subclass.
 */
public class TopicFragment extends Fragment implements AdapterView.OnItemClickListener,  ViewPager.OnPageChangeListener, RadioGroup.OnCheckedChangeListener, PullToRefreshBase.OnRefreshListener2<ListView> {
    public static final String URL1 = "http://api.ibaozou.com/api/v2/groups/%s/%s/page/%s/%s";
    public static final String URL2 = "http://api.ibaozou.com/api/v2/joke_points";
    private MainActivity mainActivity;
    private TopicArticleAdapter articleAdapter;
    private LinkedList<Article> articles;
    private ViewPager pager;
    private LinearLayout load_layout;
    private View image_error;
    private RadioGroup radioGroup;
    private MyRunnable myRunnable = new MyRunnable();
    private android.os.Handler handler = new android.os.Handler();
    private int index;
    private HttpUtils httpUtils;
    private PullToRefreshListView pullToRefreshListView;
    private ListView listView;


    private int kindId = 1;
    private String kind = "recent_hot";

    private int page = 2;
    private int size = 5;

    // at com.handmark.pulltorefresh.library.PullToRefreshListView$InternalListView.dispatchDra


    private boolean flag;



    //判断进程是否执行的标记
    private boolean mark = true;

    class MyRunnable implements Runnable {

        @Override
        public void run() {
            if (mark) {
                index++;
                index = index % 4;
                pager.setCurrentItem(index, true);
                handler.postDelayed(myRunnable, 5000);
            }
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mark = false;
    }

    public TopicFragment() {
        // Required empty public constructor
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        if (activity != null) {
            mainActivity = (MainActivity) activity;
        }
    }


    /**
     * 两个异步任务请求和相应
     */
    private void executeHttp(final String url1, String url2) {
        httpUtils = new HttpUtils();
        httpUtils.send(HttpRequest.HttpMethod.GET, url1, new RequestCallBack<String>() {

            @Override
            public void onSuccess(ResponseInfo<String> stringResponseInfo) {
                String result = stringResponseInfo.result;
                LinkedList<Article> articleLinkedList = new LinkedList<>();

                load_layout.setVisibility(View.GONE);
                image_error.setVisibility(View.GONE);
                listView.setVisibility(View.VISIBLE);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    JSONArray jsonArray = jsonObject.getJSONArray("articles");
                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject object = jsonArray.getJSONObject(i);
                        Article article = new Article();
                        article.parseJSON(object);
                        articleLinkedList.add(article);
                    }
                    if (flag) {
                        articles.clear();
                    }
                    articles.addAll(articleLinkedList);
                    articleAdapter.notifyDataSetChanged();
                    //关闭菜单，收起下拉，上来布局
                    pullToRefreshListView.onRefreshComplete();
                    flag = false;
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {
                Toast.makeText(mainActivity, "加载失败，网络问题", Toast.LENGTH_SHORT).show();
                image_error.setVisibility(View.VISIBLE);
                pullToRefreshListView.setVisibility(View.GONE);
                load_layout.setVisibility(View.GONE);
                pullToRefreshListView.setMode(PullToRefreshBase.Mode.DISABLED);
            }
        });

        httpUtils = new HttpUtils();
        httpUtils.send(HttpRequest.HttpMethod.GET, url2, new RequestCallBack<String>() {

            private LinkedList<Fragment> fragmentLinkedList;

            @Override
            public void onSuccess(ResponseInfo<String> stringResponseInfo) {

                load_layout.setVisibility(View.GONE);
                image_error.setVisibility(View.GONE);
                listView.setVisibility(View.VISIBLE);
                String result = stringResponseInfo.result;
                fragmentLinkedList = new LinkedList<>();
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    JSONArray jsonArray = jsonObject.getJSONArray("joke_points");
                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject object = jsonArray.getJSONObject(i);
                        JokePoint jokePoint = new JokePoint();
                        jokePoint.parseJSON(object);
                        Jokable jokable = jokePoint.getJokable();

                        TopicPagerFragment topicPagerFragment = new TopicPagerFragment();
                        Bundle bundle = new Bundle();
                        bundle.putSerializable(
                                "joke_point",
                                jokePoint
                        );
                        bundle.putSerializable("jokable", jokable);
                        topicPagerFragment.setArguments(bundle);
                        fragmentLinkedList.add(topicPagerFragment);
                    }

                    CommonFragmentAdapter commonFragmentAdapter = new CommonFragmentAdapter(getChildFragmentManager(), fragmentLinkedList);

                    if (pager != null) {
                        pager.setAdapter(commonFragmentAdapter);
                    }


                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {
                Toast.makeText(mainActivity, "加载失败，网络问题", Toast.LENGTH_SHORT).show();
                image_error.setVisibility(View.VISIBLE);
                pullToRefreshListView.setVisibility(View.GONE);
                load_layout.setVisibility(View.GONE);
                pullToRefreshListView.setMode(PullToRefreshBase.Mode.DISABLED);
            }
        });
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View ret = inflater.inflate(R.layout.fragment_topic, container, false);
        load_layout = (LinearLayout) ret.findViewById(R.id.load_layout);

        load_layout.setVisibility(View.VISIBLE);

        //初始化ActionBar
        mainActivity.setActionBarTitle("最热门");
        mainActivity.setBackVisible(false);
        mainActivity.setFunctionVisible(false);


        //设置下拉刷新相关属性
        pullToRefreshListView = (PullToRefreshListView) ret.findViewById(R.id.topic_articles);
        pullToRefreshListView.setMode(PullToRefreshBase.Mode.BOTH);
        pullToRefreshListView.setOnRefreshListener(this);
        //listView
        listView = pullToRefreshListView.getRefreshableView();
        articles = new LinkedList<>();
        articleAdapter = new TopicArticleAdapter(mainActivity, articles);


        View view = inflater.inflate(R.layout.item_topic_pager, null, false);

        listView.addHeaderView(view);
        pager = (ViewPager) view.findViewById(R.id.topic_pager);
        radioGroup = (RadioGroup) view.findViewById(R.id.topic_pager_switch);

        listView.setAdapter(articleAdapter);
        listView.setOnItemClickListener(this);

        View v = radioGroup.getChildAt(0);
        if (v != null) {
            if (v instanceof RadioButton) {
                RadioButton rb = (RadioButton) v;
                rb.setChecked(true);
            }
        }


        image_error = ret.findViewById(R.id.topic_image_error);
        listView.setVisibility(View.GONE);

        String url = String.format(URL1, String.valueOf(kindId), kind, "1", String.valueOf(size));
        executeHttp(url, URL2);
        return ret;
    }


    @Override
    public void onResume() {
        super.onResume();


        pager.setOnPageChangeListener(this);

        radioGroup.setOnCheckedChangeListener(this);

        new Thread(myRunnable).start();
        handler.postDelayed(myRunnable, 1000);
    }

    //////////////////////////联动效果设置/////////////////////////////////
    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        int rbCount = group.getChildCount();

        // 处理步骤 2: 如果能够获取到RadioGroup中的每一个RadioButton
        //            我们判断以下RadioButton是否选中，
        //            我们采用循环来获取，如果选中，即可得到 索引位置
        //            容器提供 getChildAt(int index) 方法，来获取子控件

        int position = -1;

        for (int index = 0; index < rbCount; index++) {
            View v = group.getChildAt(index);
            if (v != null && v instanceof RadioButton) {
                RadioButton rb = (RadioButton) v;
                // 可以通过 RadioButton 的 isChecked() 判断是否选中了
                if (rb.isChecked()) {
                    position = index;
                    break;
                }
            }
        }

        Log.d("DetailActivity", "onCheckdChange " + position);

        if (position > -1) {
            pager.setCurrentItem(position, true);
        }
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
// 根据位置，找到RadioGroup中，所有的RadioButton
        // 设置指定索引位置的RadioButton选中。
        //

        View v = radioGroup.getChildAt(position);

        if (v != null) {
            if (v instanceof RadioButton) {
                RadioButton rb = (RadioButton) v;
                rb.setChecked(true);
                Log.d("DetailActivity", "onPageSelected setChecked");
            }
        }

    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        int headerViewsCount = listView.getHeaderViewsCount();
        Article article = articles.get(position - headerViewsCount);
        Intent intent;

        if (!article.getPictures().equals("")) {
            String pictures = article.getPictures();
            intent = new Intent(mainActivity, TopicPicturesDetailActivity.class);
            intent.putExtra("pictures", pictures);
        } else {
            String mp4_file_link = article.getMp4_file_link();
            intent = new Intent(mainActivity, TopicPagerMovieActivity.class);
            intent.putExtra("mp4_file_link", mp4_file_link);
        }
        startActivity(intent);
    }

    //下拉刷新，上拉加载回调函数
    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
        flag = true;
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                String url = String.format(URL1, String.valueOf(kindId), kind, "1", String.valueOf(size));
                executeHttp(url, URL2);
            }
        }, 2000);

    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                String url = String.format(URL1, String.valueOf(kindId), kind, String.valueOf(page), String.valueOf(size));
                executeHttp(url, URL2);
                page++;
            }
        }, 2000);

    }



    @Override
    public void onDestroy() {
        Log.e("TopicFragment", "onDestroy");
        super.onDestroy();
    }
}
